<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区名称" prop="communityId" >
        <el-select v-model="queryParams.communityId" placeholder="请选择社区ID" style="width: 100px">
          <el-option label="阳光花园" value="1"></el-option>
          <el-option label="绿城雅苑" value="2"></el-option>
          <el-option label="山水名都" value="3"></el-option>
          <el-option label="枫林壹号" value="4"></el-option>
          <el-option label="湖园家园" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号" prop="carNo">
        <el-input
            v-model="queryParams.carNo"
            placeholder="请输入车牌号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车主姓名" prop="ownerName">
        <el-input
            v-model="queryParams.ownerName"
            placeholder="请输入车主姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车主手机号" prop="ownerPhone" label-width="100px">
        <el-input
            v-model="queryParams.ownerPhone"
            placeholder="请输入车主手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位编号" prop="parkingSpaceNo">
        <el-input
            v-model="queryParams.parkingSpaceNo"
            placeholder="请输入车位编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出入闸机" prop="gateDevice">
        <el-select v-model="queryParams.gateDevice" placeholder="请选择出入闸机" style="width: 100px">
          <el-option label="东门主闸机" value="东门主闸机"></el-option>
          <el-option label="南门临时通道" value="南门临时通道"></el-option>
          <el-option label="西门智能闸机" value="西门智能闸机"></el-option>
          <el-option label="北门人工通道" value="北门人工通道"></el-option>
          <el-option label="东门应急通道" value="东门应急通道"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" style="width: 100px">
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="微信" value="微信"></el-option>
          <el-option label="年卡" value="年卡"></el-option>
          <el-option label="季卡" value="季卡"></el-option>
          <el-option label="月卡" value="月卡"></el-option>
          <el-option label="免费" value="免费"></el-option>
          <el-option label="未支付" value="未支付"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入场时间" prop="entryTime">
        <el-date-picker clearable
                        v-model="queryParams.entryTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择入场时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出场时间" prop="exitTime">
        <el-date-picker clearable
                        v-model="queryParams.exitTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择出场时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="费用" prop="fee">
        <el-input
            v-model="queryParams.startFee"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
            style="width: 70px"
        />
        <span style="margin: 0 5px">至</span>
        <el-input
            v-model="queryParams.endFee"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
            style="width: 70px"
        />


      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:record:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:record:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:record:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:record:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="记录ID" align="center" prop="recordId"/>
      <el-table-column label="社区名称" align="center" prop="communityId" :formatter="formatCommunityName"/>
      <el-table-column label="车牌号" align="center" prop="carNo"/>
      <el-table-column label="车辆类型" align="center" prop="vehicleType"/>
      <el-table-column label="车主姓名" align="center" prop="ownerName"/>
      <el-table-column label="车主手机号" align="center" prop="ownerPhone"/>
      <el-table-column label="车位编号" align="center" prop="parkingSpaceNo"/>
      <el-table-column label="出入闸机" align="center" prop="gateDevice"/>
      <el-table-column label="支付方式" align="center" prop="paymentMethod"/>
      <el-table-column label="入场时间" align="center" prop="entryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出场时间" align="center" prop="exitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.exitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status"/>
      <el-table-column label="费用" align="center" prop="fee"/>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">

          <template v-if="scope.row.status === '在场'">

            <el-button
                link
                type="warning"
                icon="el-icon-circle-minus-outline"
                @click="handleLeave(scope.row)"
                :disabled="isSubmitting"
                v-hasPermi="['system:record:remove']"
            >
              车辆离场
            </el-button>
          </template>
          <template v-else>

            <el-button
                link
                type="success"
                icon="el-icon-circle-plus-outline"
                @click="handleEnter(scope.row)"
                :disabled="isSubmitting"
                v-hasPermi="['system:record:edit']"
            >
              车辆入场
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:record:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:record:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改record对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="社区ID" prop="communityId">

          <el-select v-model="form.communityId" placeholder="请选择社区ID">
            <el-option label="阳光花园" value="1"></el-option>
            <el-option label="绿城雅苑" value="2"></el-option>
            <el-option label="山水名都" value="3"></el-option>
            <el-option label="枫林壹号" value="4"></el-option>
            <el-option label="湖园家园" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="carNo">
          <el-input v-model="form.carNo" placeholder="请输入车牌号"/>
        </el-form-item>
        <el-form-item label="车主姓名" prop="ownerName">
          <el-input v-model="form.ownerName" placeholder="请输入车主姓名"/>
        </el-form-item>
        <el-form-item label="车主手机号" prop="ownerPhone">
          <el-input v-model="form.ownerPhone" placeholder="请输入车主手机号"/>
        </el-form-item>
        <el-form-item label="车位编号" prop="parkingSpaceNo">
          <el-input v-model="form.parkingSpaceNo" placeholder="请输入车位编号"/>
        </el-form-item>
        <el-form-item label="出入闸机" prop="gateDevice">
          <el-select v-model="form.gateDevice" placeholder="请选择出入闸机" style="width: 100px">
            <el-option label="东门主闸机" value="东门主闸机"></el-option>
            <el-option label="南门临时通道" value="南门临时通道"></el-option>
            <el-option label="西门智能闸机" value="西门智能闸机"></el-option>
            <el-option label="北门人工通道" value="北门人工通道"></el-option>
            <el-option label="东门应急通道" value="东门应急通道"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" style="width: 100px">
            <el-option label="支付宝" value="支付宝"></el-option>
            <el-option label="微信" value="微信"></el-option>
            <el-option label="年卡" value="年卡"></el-option>
            <el-option label="季卡" value="季卡"></el-option>
            <el-option label="月卡" value="月卡"></el-option>
            <el-option label="免费" value="免费"></el-option>
            <el-option label="未支付" value="未支付"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入场时间" prop="entryTime">
          <el-date-picker clearable
                          v-model="form.entryTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择入场时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出场时间" prop="exitTime">
          <el-date-picker clearable
                          v-model="form.exitTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择出场时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="社区名称" prop="communityName">
          <el-select v-model="form.communityName" placeholder="请选择社区名称" style="width: 100px">
            <el-option label="阳光花园" value="阳光花园"></el-option>
            <el-option label="绿城雅苑" value="绿城雅苑"></el-option>
            <el-option label="山水名都" value="山水名都"></el-option>
            <el-option label="湖畔家园" value="湖畔家园"></el-option>
            <el-option label="湖畔家园" value="湖畔家园"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入费用"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>




<script setup name="Record">
import {listRecord, getRecord, delRecord, addRecord, updateRecord} from "@/api/system/record"
import {inRecord, outRecord} from "../../../api/system/record.js";

const {proxy} = getCurrentInstance()

const recordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const isSubmitting = ref( false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    carNo: null,
    vehicleType: null,
    ownerName: null,
    ownerPhone: null,
    parkingSpaceNo: null,
    gateDevice: null,
    paymentMethod: null,
    entryTime: null,
    exitTime: null,
    communityName: null,
    status: null,
    startFee: null,
    endFee: null,
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)


const communityDict = {
  1: '阳光花园',
  2: '绿城雅苑',
  3: '山水名都',
  4: '枫林壹号',
  5: '湖畔家园'
};

// 单独定义格式化方法（与其他方法同级）
const formatCommunityName = (row) => {
  // 注意：row.communityId 可能是字符串类型，需转数字匹配字典键
  return communityDict[Number(row.communityId)] || row.communityId;
};

/** 查询record列表 */
function getList() {
  loading.value = true
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    communityId: null,
    carNo: null,
    vehicleType: null,
    ownerName: null,
    ownerPhone: null,
    parkingSpaceNo: null,
    gateDevice: null,
    paymentMethod: null,
    entryTime: null,
    exitTime: null,
    communityName: null,
    status: null,
    fee: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("recordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加record"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _recordId = row.recordId || ids.value
  getRecord(_recordId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改record"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value
  proxy.$modal.confirm('是否确认删除record编号为"' + _recordIds + '"的数据项？').then(function () {
    return delRecord(_recordIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}





/** 车辆入场 */
// 必须声明为 async 函数，才能使用 await
async function handleEnter(row) {
  if (isSubmitting.value) {
    proxy.$modal.msgWarning("操作处理中，请稍后...");
    return;
  }

  isSubmitting.value = true; // 锁定

  try {
    row.status = '在场';
    // 关键：用 await 等待异步请求完成，获取实际响应结果
    const resp = await inRecord(row);

    // 此时 resp 才是后端返回的实际数据（含 code、msg 等）
    if (resp.code === 200) {
      proxy.$modal.msgSuccess("车辆入场成功");
      getList();
    } else {
      proxy.$modal.msgError(resp.msg || "操作失败，请重试");
    }
  } catch (error) {
    proxy.$modal.msgError(error.message || "网络异常，请重试");
  } finally {
    // 等待请求完成后再解锁（加延迟进一步防重复）
    setTimeout(()=>{
      isSubmitting.value = false;
    },1000)
  }
}

/** 车辆离场 */
// 同样声明为 async 函数
async function handleLeave(row) {
  if (isSubmitting.value) {
    proxy.$modal.msgWarning("操作处理中，请稍后...");
    return;
  }

  isSubmitting.value = true; // 锁定

  try {
    row.status = '离场';

      const resp = await outRecord(row);

    if (resp.code === 200) { // 按后端实际响应判断
      proxy.$modal.msgSuccess("车辆离场成功");
      getList();
    } else {
      proxy.$modal.msgError(resp.msg || "操作失败，请重试");
    }
  } catch (error) {
    proxy.$modal.msgError(error.message || "网络异常，请重试");
  } finally {
    setTimeout(()=>{
      isSubmitting.value = false;
    },1000)
  }
}
getList()
</script>
